package com.geovis.emergency.spd.handler;

import cn.hutool.core.util.ObjectUtil;
import com.geovis.common.auth.util.AuthUtil;
import com.geovis.common.core.dto.CacheAuthUser;
import com.geovis.common.web.handler.MybatisPlusMetaObjectHandler;
import com.geovis.emergency.spd.cache.DeptCache;
import com.geovis.emergency.spd.entity.pc.pojo.enums.StatusEnum;
import com.geovis.emergency.spd.entity.system.entity.SystemDept;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * <p>
 *
 * </p>
 *
 * @author Lonsho
 * @version 1.0
 * @date 2022/6/18
 */
@Primary
@Component
public class SpdMetaObjectHandler extends MybatisPlusMetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        super.insertFill(metaObject);
        CacheAuthUser currUser = AuthUtil.getCurrUser();
        if (ObjectUtil.isNotNull(currUser)){
            this.strictInsertFill(metaObject,"createDept", String.class, currUser.getDeptId());
            this.strictInsertFill(metaObject,"senderId", String.class, currUser.getUserId());

            SystemDept currentDept = DeptCache.getCurrentDept();
            if (ObjectUtil.isNotNull(currentDept)){
                this.strictInsertFill(metaObject,"regionCode",String.class,currentDept.getRegionCode());
            }
        }
        this.strictInsertFill(metaObject,"isDeleted", String.class, StatusEnum.FALSE.getCode());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        String username = AuthUtil.getCurrentUsername();
        if (ObjectUtil.isNotNull(username)) {
            this.setFieldValByName("updateBy", username,metaObject);
        }
        this.setFieldValByName("updateTime", LocalDateTime.now(),metaObject);
    }
}
